#include "connection.hpp"

bool auto_ack = true;

void consumeCallback(mq::Channel::ptr &channel, const string &consumer_tag, const BasicProperties *bp, const string &body)
{
    cout << consumer_tag << " 消费了消息 " << body << endl;
    if (!auto_ack)
        channel->basicAck(bp->id()); // 手动应答
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        DLOG("Usage:./consume_client ctag qname");
        return -1;
    }
    // 1.实例化异步工作线程对象
    AsyncWorker::ptr worker = make_shared<AsyncWorker>();
    // 2.实例化连接对象
    Connection::ptr conn = make_shared<Connection>("127.0.0.1", 8080, worker);
    conn->connect();
    // 3.创建信道
    mq::Channel::ptr channel = conn->openChannel();
    if (channel.get() == nullptr)
    {
        DLOG("打开信道失败");
        return 0;
    }
    else
        DLOG("打开信道成功:cid %s", channel->get_cid().c_str());

    // 4.通过信道完成：
    //      1.声明交换机exchange1（广播），队列queue1和queue2
    Map map;
    channel->declareExchange("exchange1", TOPIC, true, true, map);
    channel->declareMsgQueue("queue1", false, true, true, map);
    channel->declareMsgQueue("queue2", false, true, true, map);
    //      2.绑定ex1和q1，bingkey = queue1
    channel->Bind("exchange1", "queue1", "a.*");
    //      3.绑定ex1和q2，bingkey = new.music.#
    channel->Bind("exchange1", "queue2", "a.b.#");
    //      4.订阅队列
    auto functor = std::bind(&consumeCallback, channel, placeholders::_1, placeholders::_2, placeholders::_3);
    channel->basicConsume(argv[1], argv[2], auto_ack, functor);
    while (1)
        this_thread::sleep_for(chrono::seconds(3)); // 卡住主线程
    // 5.关闭信道
    conn->closeChannel(channel);
    // 6.关闭连接
    return 0;
}